namespace _79 {

var exist79 = function(board: string[], word: string): boolean {

    function loop(row: number, col: number, position: number, matrix: string[][]): boolean {
        if (row < 0 
            || row >= matrix.length 
            || col < 0 
            || col >= matrix[row].length
            || position > word.length
            || word[position] !== matrix[row][col]) 
            return false

        matrix[row][col] = '#'

        if (position + 1 === word.length 
            || loop(row, col + 1, position + 1, matrix)
            || loop(row + 1, col, position + 1, matrix)
            || loop(row, col - 1, position + 1, matrix)
            || loop(row - 1, col, position + 1, matrix))
            return true

        matrix[row][col] = word[position]
        return false
    }

    for(var i = 0; i < board.length; i++)
        for(var j = 0; j < board[i].length; j++)
            if ( loop(i, j, 0, board.map(x => x.split('')) )) 
                return true;

    return false
};

var board79: string[]

board79 = [
  'ABCE',
  'SFCS',
  'ADEE'
]

console.assert( exist79( board79, "ABCCED"))
console.assert( exist79( board79, "ABCB") === false)
console.assert( exist79( board79, "SEE"))

board79 = [
    "ABCE",
    "SFES",
    "ADEE"
]

console.assert( exist79( board79, "ABCESEEEFS"))

board79 = [
  'ab',
  'cd',
]

console.assert( exist79( board79, "cdba"))


console.log('The END')


}